#include "jxlencoder.h"
#include <QFile>
//#include <QCryptographicHash>
//#include <QDebug>

jxlEncoder::jxlEncoder()
{

    //并行下不知道当前回调的程序在跑哪张图片
//    cjxlencoder=new QProcess(this);
//    connect(cjxlencoder,static_cast<void(QProcess::*)(int, QProcess::ExitStatus)>(&QProcess::finished),this,&jxlEncoder::Verify);//转换后触发验证

//    jxldecoder=new QProcess(this);
//    connect(jxldecoder,static_cast<void(QProcess::*)(int, QProcess::ExitStatus)>(&QProcess::finished),this,&jxlEncoder::hashVerify);//转换后触发验证
}

bool jxlEncoder::inputTask(QStringList input, QStringList output, QStringList parameter, bool deleteSource, bool reverify,int CoreUsage)
{
    if(state()!=0){
        return false;//有任务正在运行，拒绝任务
    }

    //初始化
    TaskList.clear();
    errTaskNum=0;

    inputList=input;
    outputList=output;
    parameterList=parameter;
    delSource=deleteSource;
    reVerify=reverify;
    threadPool.setMaxThreadCount(CoreUsage);

    Convert();
    return true;
}

void jxlEncoder::Convert()//转换
{
    //直接发送全部任务到线程池，让线程池去管理
    for(int index=0;index<inputList.size();index++){
        //输入文件不存在,报错并开始下一个
        if(!QFile::exists(inputList.at(index))){
            emit convertLog("\njxlgui:"+inputList.at(index)+" file does not exist.\n");
            emit convertResult(index,0);
        }
        else{
            QString argument='"'+inputList.at(index)+'"'+" "+'"'+outputList.at(index)
                    +'"'+" "+parameterList.at(index);//文件名加引号，防止文件名含空格
            QString outputTarget=outputList.at(index);
            QString inputTarget=inputList.at(index);

            SingleProcesstask* newJXLTask=new SingleProcesstask(index,argument,inputTarget,outputTarget,reVerify,delSource);
            connect(newJXLTask, SIGNAL(convertResult(int,int)), this,
                    SLOT(convertResultRelay(int,int)), Qt::QueuedConnection);
            connect(newJXLTask, SIGNAL(convertLog(QString)), this,
                    SLOT(convertLogRelay(QString)), Qt::QueuedConnection);
            threadPool.start(newJXLTask);

        }
    }

}

int jxlEncoder::state()
{
//    qDebug()<<threadPool.activeThreadCount();
    return threadPool.activeThreadCount();//正在工作的线程数为0说明当前任务完成，那么就不用拒绝任务了
}

void jxlEncoder::convertLogRelay(QString Log)
{
    emit convertLog(Log);
}

void jxlEncoder::convertResultRelay(int num, int result)
{
    emit convertResult(num,result);
}
